from email.mime.text import MIMEText
from email.utils import formataddr
from config.settings import get_settings
import smtplib
import concurrent.futures
import time
from get_logger import get_error_logger, get_server_logger


error_logger = get_error_logger()
server_logger = get_server_logger()


# 提前实例化线程池
executor = concurrent.futures.ThreadPoolExecutor(max_workers=4)

settings = get_settings()

__all__ = [
    'thread_pool_send_email',
]


def thread_pool_send_email(recipient_email, subject, message):
    """
    Args:
        recipient_email (_type_): 收件人
        subject (_type_): 标题
        message (_type_): 内容
    """
    future = executor.submit(send_email_when_check_eform, recipient_email, subject, message)
    future.add_done_callback(lambda f: server_logger.info(f"Email sent to {recipient_email}"))
    # return future.result()

# def thread_send_email(recipient_email, subject, message):
#     """
#     Args:
#         recipient_email (_type_): 收件人
#         subject (_type_): 标题
#         message (_type_): 内容
#     """
#     email_thread = threading.Thread(
#         target=send_email_when_check_eform, args=(recipient_email, subject, message,))
#     email_thread.start()


def send_email_when_check_eform(recipient_email, subject, message):
    """
    Args:
        recipient_email (_type_): 收件人
        subject (_type_): 标题
        message (_type_): 内容
    """
    from_addr = formataddr(("CEWS", settings.SERVER_EMAIL))
    to_addr = recipient_email

    msg = MIMEText(message, 'html')
    msg['From'] = from_addr
    msg['To'] = to_addr
    msg['Subject'] = subject

    max_retries = 3
    for attempt in range(max_retries):
        try:
            server = smtplib.SMTP(settings.SMTP_SERVER, settings.SMTP_PORT)
            server.starttls()
            server.ehlo()
            server.login(settings.SERVER_EMAIL, settings.EMAIL_PASSWORD)
            server.sendmail(from_addr, to_addr, msg.as_string())
            server_logger.info('Email sent successfully')
            break  # 发送成功，退出循环
        except Exception as e:
            error_logger.error(f'Email sending failed on attempt {attempt + 1}: {str(e)}')
            if attempt < max_retries - 1:
                time.sleep(2 ** attempt)  # 指数退避，等待一段时间后重试
        finally:
            if server:
                server.quit()